import numpy as np
import wave
import struct
import matplotlib.pyplot as plt



'''

正弦波公式：y(t)= A * sin(2 * pi * f *t)

A 是幅值.
pi 是3.14159.
f 是频率.
t 是样本（也就是横坐标上质点的位置）. 由于我们需要将其转换为数字，我们将按采样率进行划分.

'''


def create_sin_wav():
    # frequency is the number of times a wave repeats a second
    frequency = 1000
    # The sampling rate of the analog to digital convert
    sampling_rate = 41400
    amplitude = 16000
    seconds = 10
    num_samples = sampling_rate * 2 * seconds

    frequency = 100
    file = "test-100.wav"
    sin_wav(frequency, num_samples, sampling_rate, amplitude, file)

    frequency = 200
    file = "test-200.wav"
    sin_wav(frequency, num_samples, sampling_rate, amplitude, file)

    frequency = 400
    file = "test-400.wav"
    sin_wav(frequency, num_samples, sampling_rate, amplitude, file)

    frequency = 600
    file = "test-600.wav"
    sin_wav(frequency, num_samples, sampling_rate, amplitude, file)

    frequency = 800
    file = "test-800.wav"
    sin_wav(frequency, num_samples, sampling_rate, amplitude, file)

    frequency = 1000
    file = "test-1k.wav"
    sin_wav(frequency, num_samples, sampling_rate, amplitude, file)

    file = "test-1.5k.wav"
    frequency = 1500
    sin_wav(frequency, num_samples, sampling_rate, amplitude, file)

    file = "test-2k.wav"
    frequency = 2000
    sin_wav(frequency, num_samples, sampling_rate, amplitude, file)

    file = "test-5k.wav"
    frequency = 5000
    sin_wav(frequency, num_samples, sampling_rate, amplitude, file)

    file = "test-10k.wav"
    frequency = 10000
    sin_wav(frequency, num_samples, sampling_rate, amplitude, file)


def sin_wav(frequency, num_samples, sampling_rate, amplitude, file):
    print("make sin wav file:")
    print("freq=%d, num_samples=%d, smpleing_rate=%d, amplitude=%d, file=%s" %
          (frequency, num_samples, sampling_rate, amplitude, file))

    sine_wave = [np.sin(2 * np.pi * frequency * x/sampling_rate) for x in range(num_samples)]
    nframes = num_samples
    comptype = "NONE"
    compname = "not compressed"
    nchannels = 2
    sampwidth = 2

    wav_file = wave.open(file, 'w')
    wav_file.setparams((nchannels, sampwidth, int(sampling_rate), nframes, comptype, compname))
    for s in sine_wave:
        wav_file.writeframes(struct.pack('h', int(s * amplitude)))



if __name__ == '__main__':
    create_sin_wav()

